package com.ruoyi.inducePest.controller.InducePest;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.inducePest.domain.InduceDetectionLog;
import com.ruoyi.inducePest.domain.inducePest.InducePestImgInfo;
import com.ruoyi.inducePest.domain.inducePest.SelectInducePestImgInfo;
import com.ruoyi.inducePest.mapper.device.InduceDeviceMapper;
import com.ruoyi.inducePest.mapper.inducePest.InducePestImgMapper;
import com.ruoyi.inducePest.service.inducePest.InducePestCaptureImgService;
import com.ruoyi.traplight.domain.SelectPhotoDao;
import com.ruoyi.traplight.domain.TagAndCorner;
import com.ruoyi.utils.ParseString;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author DELL
 */
@Api("图片下载控制类")
@Slf4j
@RestController
@RequestMapping("/inducePest/info")
public class InducePestImgController extends BaseController {

    @Autowired
    private InducePestCaptureImgService inducePestCaptureImgService;

    @Autowired
    private InduceDeviceMapper induceDeviceMapper;

    @Autowired
    private InducePestImgMapper inducePestImgMapper;



    /**
     * 根据条件查询出所有结果
     * @param inducePestImgInfo
     * @return
     */
//    @ApiOperation("根据条件查询列表，支持分页使用 numSize、numPage.根据时间查找，加上beginTime和end参数示例如下：" +
//            "http://localhost:8182/inducePest/info/getInfoByCondition")
    @PostMapping("/getInfoByCondition")
            public TableDataInfo getInfoByCondition(SelectInducePestImgInfo inducePestImgInfo, Integer pageNum, Integer pageSize) throws JsonProcessingException {
        if(inducePestImgInfo.getEndTime()!=null) {
            Calendar now = Calendar.getInstance();
            now.setTime(inducePestImgInfo.getEndTime());
            now.set(Calendar.DATE, now.get(Calendar.DATE) + 1);
            inducePestImgInfo.setEndTime(now.getTime());
        }
//        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
//        inducePestImgInfo.setUserId(Integer.valueOf(userId.intValue()));
//        if(inducePestImgInfo.getUserId()==1){
//            inducePestImgInfo.setUserId(null);
//        }
        TableDataInfo tableDataInfo = inducePestCaptureImgService.getInfoByCondition(inducePestImgInfo, pageNum, pageSize);
        return tableDataInfo;
    }

    /**
     * 根据条件查询出害虫种类
     * @param inducePestImgInfo
     * @return
     */
//    @ApiOperation("根据条件查询列表，支持分页使用 numSize、numPage.根据时间查找，加上beginTime和end参数示例如下：" +
//            "http://localhost:8182/inducePest/info/getPestTypeInfoByCondition")
    @PostMapping("/getPestTypeInfoByCondition")
    public AjaxResult getPestTypeInfoByCondition(SelectInducePestImgInfo inducePestImgInfo) {
        if(inducePestImgInfo.getEndTime()!=null) {
            Calendar now = Calendar.getInstance();
            now.setTime(inducePestImgInfo.getEndTime());
            now.set(Calendar.DATE, now.get(Calendar.DATE) + 1);
            inducePestImgInfo.setEndTime(now.getTime());
        }
        //Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        //inducePestImgInfo.setUserId(Integer.valueOf(userId.intValue()));
        //if(inducePestImgInfo.getUserId()==1){
        //    inducePestImgInfo.setUserId(null);
        //}
        List<String> pestTypes = inducePestCaptureImgService.getPestTypeInfoByCondition(inducePestImgInfo);
        return AjaxResult.success(pestTypes);
    }

    /**
     * 根据条件查询出害虫种类
     * @param
     * @return
     */
//    @ApiOperation("根据条件查询列表，支持分页使用 numSize、numPage.根据时间查找，加上beginTime和end参数示例如下：" +
//            "http://localhost:8182/inducePest/info/getPestTypeInfoByCondition")
    @PostMapping("/getPestTypeInfoByConditionForDevices")
    public AjaxResult getPestTypeInfoByConditionForDevices(String beginTime, String endTime, @RequestParam(value ="deviceIds",required = false) String deviceIdsString) {
        //生成设备列表
        ArrayList<Integer> deviceIds = new ArrayList<>();
        if(StringUtils.isNotBlank(deviceIdsString)) {
            if (deviceIdsString.contains(",")) {
                for (String s : deviceIdsString.split(",")) {
                    deviceIds.add(Integer.parseInt(s));
                }
            } else {
                deviceIds.add(Integer.parseInt(deviceIdsString));
            }
        }
        SelectInducePestImgInfo selectInducePestImgInfo = new SelectInducePestImgInfo();
        List<String> result=new ArrayList<>();
        for (Integer deviceId: deviceIds) {
            selectInducePestImgInfo.setDeviceId(deviceId);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

            try {
                Date beginDate = format.parse(beginTime);
                selectInducePestImgInfo.setBeginTime(beginDate);
                Date endDate = format.parse(endTime);
                selectInducePestImgInfo.setEndTime(endDate);
            } catch (ParseException e) {
                e.printStackTrace();
            }

            List<String> pestTypes = inducePestCaptureImgService.getPestTypeInfoByCondition(selectInducePestImgInfo);
            result.addAll(pestTypes);
            HashSet<String> set = new HashSet<>(result);
            result = new ArrayList<>(set);
        }
        return AjaxResult.success(result);
    }


    @ApiOperation("调用模型检测,示例：http://localhost:8182/inducePest/info/insertInfoForMultipartFile")
    @PostMapping("/insertInfoForMultipartFile")
    public AjaxResult insertInfoForMultipartFile(@RequestParam("files") MultipartFile[] files) throws Exception {
        if(files.length!=0){

            List<InduceDetectionLog> result = inducePestCaptureImgService.insertInfoForMultipartFile(files);
            return AjaxResult.success(result);
        }else {
            return AjaxResult.error("上传图片异常");
        }
    }


    @ApiOperation("调用模型检测,示例：http://localhost:8182/inducePest/info/insertInfoForSingleDetail")
    @PostMapping("/insertInfoForSingleDetail")
    public AjaxResult insertInfoForSingleDetail(@RequestParam("file") MultipartFile file,InducePestImgInfo inducePestImgInfo) throws Exception {
        if (!file.isEmpty()) {

            List<InduceDetectionLog> result = inducePestCaptureImgService.insertInfoForSingleDetail(file, inducePestImgInfo);
            return AjaxResult.success(result);
        }else {
            return AjaxResult.error("上传图片异常");
        }
    }

    /**
     * 重新自动计数
     * @param id 记录编号
     * @return
     */
    @ApiOperation("重新自动计数" +
            "http://localhost:8182/tobacco/autoCountAgain")
    @GetMapping("/autoCountAgain")
    public AjaxResult autoCountAgain(int id) throws JsonProcessingException {
        List<InduceDetectionLog> InduceDetectionLogs = inducePestCaptureImgService.autoCountAgain(id);

        return AjaxResult.success(InduceDetectionLogs);
    }

    /**
     * 修改是否是新板的状态
     * @param id 记录编号
     * @return
     */
//    @ApiOperation("修改是否是新板的状态" +
//            "http://localhost:8182/inducePest/info/updateBoard")
    @GetMapping("/updateBoard")
    public AjaxResult updateBoard(Integer id,Integer isNewBoard) {
        Integer integer = inducePestCaptureImgService.updateBoard(id, isNewBoard);
        if(integer>0){
            return AjaxResult.success("修改成功");
        }else {
            return AjaxResult.error("修改失败，查看主键是否匹配");
        }
    }
    /**
     * 修改人工标签数量
     * @param id 记录编号
     * @return
     */
//    @ApiOperation("修改人工标签数量" +
//            "http://localhost:8182/inducePest/info/updateTagManual")
    @GetMapping("/updateTagManual")
    public AjaxResult updateTagManual(Integer id, Integer dm, Integer ehm, Integer dzjym, Integer cdtye, Integer ymm) {
        Integer integer = inducePestCaptureImgService.updateTagManual(id, dm, ehm, dzjym, cdtye,ymm);
        if(integer>0){
            return AjaxResult.success("修改成功");
        }else {
            return AjaxResult.error("修改失败，查看主键是否匹配");
        }
    }

    /**
     * 删除数据
     * @param id
     * @return
     */
    @GetMapping("/deleteImageById")
    public AjaxResult deleteImageById(int id){
        Integer counts = inducePestCaptureImgService.deleteImgInfo(id);
        if(counts==0){
            return AjaxResult.success("该信息在数据库中不存在，请刷新或联系管理员");
        }
        return AjaxResult.success("删除成功，请刷新");

    }

    /**
     * 拉取前一天的图片信息到数据库
     *
     * @return
     */
//    @ApiOperation("拉取前一天的图片信息到数据库" +
//            "http://localhost:8182/inducePest/info/downImageFromOSS")
    @GetMapping("/downImageFromOSS")
    public AjaxResult downImageFromOSS() throws ParseException {
        List<InduceDetectionLog> InduceDetectionLogs = inducePestCaptureImgService.downImageFromOSSAuto();
        if(InduceDetectionLogs.size()>0){
            return AjaxResult.success(InduceDetectionLogs);
        }else {
            return AjaxResult.success("当天所有图片均未检测出目标");
        }
    }





    /**
     * 更新绘图信息以及虫子信息
     *
     * @return
     */
//    @ApiOperation("更新绘图信息以及虫子信息" +
//            "http://localhost:8182/inducePest/info/drawByManual")
    @PostMapping("/drawByManual")
    public AjaxResult drawByManual(Integer id,String width,String height,String type,String typeName,String position,Integer addOrCut) throws IOException {
        if((!StringUtils.isEmpty(typeName) &&typeName.equals("草地贪夜蛾")) || (!StringUtils.isEmpty(type) &&type.equals("草地贪夜蛾"))){
            type="cdtye";
        }
        if((!StringUtils.isEmpty(typeName) &&typeName.equals("稻纵卷叶螟"))|| (!StringUtils.isEmpty(type) &&type.equals("稻纵卷叶螟"))){
            type="dzjym";
        }
        if((!StringUtils.isEmpty(typeName) &&typeName.equals("二化螟"))|| (!StringUtils.isEmpty(type) &&type.equals("二化螟"))){
            type="ehm";
        }
        if((!StringUtils.isEmpty(typeName) &&typeName.equals("大螟"))|| (!StringUtils.isEmpty(type) &&type.equals("大螟"))){
            type="dm";
        }
        if((!StringUtils.isEmpty(typeName) &&typeName.equals("玉米螟"))|| (!StringUtils.isEmpty(type) &&type.equals("玉米螟"))){
            type="ymm";
        }
        if(StringUtils.isEmpty(type)){
            type="cdtye";
        }
        InducePestImgInfo result = inducePestCaptureImgService.drawByManual(id, width, height, type, position,addOrCut);

        return AjaxResult.success(result);


    }


    /**
     * 拉取指定时间段的的图片信息到数据库
     *
     * @return
     */
//    @ApiOperation("拉取指定时间段的的图片信息到数据库" +
//            "http://localhost:8182/inducePest/info/downImageFromOSSByTime")
    @GetMapping("/downImageFromOSSByTime")
    public AjaxResult downImageFromOSSByTime(String beginDay,String endDay) throws ParseException {
        List<InduceDetectionLog> InduceDetectionLogs = inducePestCaptureImgService.downImageFromOSSAutoByTime(beginDay,endDay);
        if(InduceDetectionLogs.size()>0){
            return AjaxResult.success(InduceDetectionLogs);
        }else {
            return AjaxResult.success("当天所有图片均未检测出目标");
        }
    }

    /**
     * 拉取指定时间段的的图片信息到数据库
     *
     * @return
     */
//    @ApiOperation("拉取指定时间段的的图片信息到数据库" +
//            "http://localhost:8182/inducePest/info/downImageFromOSSByTimeAndCameraId")
    @GetMapping("/downImageFromOSSByTimeAndCameraId")
    public AjaxResult downImageFromOSSByTimeAndCameraId(Integer deviceId, String beginDay,String endDay) {
        List<InduceDetectionLog> InduceDetectionLogs = inducePestCaptureImgService.downImageFromOSSByTimeAndDeviceId(deviceId,beginDay,endDay);
        if(InduceDetectionLogs.size()>0){
            return AjaxResult.success(InduceDetectionLogs);
        }else {
            return AjaxResult.success("当天所有图片均未检测出目标");
        }
    }

    /**
     * 根据tag修改结果图
     *
     * @return
     */
    @GetMapping("/draw")
    public AjaxResult draw(String tag, String imgPath,String corner,String imgPest) {
        inducePestCaptureImgService.draw(tag, imgPath,corner,imgPest);

        return AjaxResult.success();

    }

    @ApiOperation("前端画框更新数据库值")
    @PostMapping("/getCornerAndTag")
    public AjaxResult getCornerAndTag(@RequestBody TagAndCorner tagAndCorner){
//        Long userIdL = SecurityUtils.getLoginUser().getUser().getUserId();
//        Integer userId=Integer.valueOf(userIdL.intValue());
        int id = tagAndCorner.getId();
        if(tagAndCorner.getCorner().equals("[]") || tagAndCorner.getTagForDraw().equals("[]")) {
            InducePestImgInfo newPhoto = new InducePestImgInfo().setId(id).setCorner("").setTagForDraw("").setTagManual("");
            inducePestImgMapper.updateInfoById(newPhoto);
        }else {
            String corner = tagAndCorner.getCorner();
            corner = corner.replaceAll("\\[","").replaceAll("]","");
            corner = corner + ",";
//        [\"y1\",\"y1\"]//解析成["y1","y1"]格式
            String tagForDraw = tagAndCorner.getTagForDraw();
//        移除字符串中的转义符号\
            String cleanedString = tagForDraw.replace("\\", "");
//        移除首尾的[ 和 ]
            tagForDraw = cleanedString.substring(1, cleanedString.length() - 1);
            // 将字符串以逗号分隔成多个子字符串
            String[] array = tagForDraw.split(",");

//        // 移除子字符串首尾的双引号 "
//        for (int i = 0; i < array.length; i++) {
//            array[i] = array[i].replaceAll("\"", "").trim();
//        }

            String tagForDrawRes = Arrays.toString(array);
            String tagManual = ParseString.getTagNum(tagForDrawRes);
            InducePestImgInfo newPhoto = new InducePestImgInfo().setId(id).setCorner(corner).setTagForDraw(tagForDrawRes).setTagManual(tagManual);
            inducePestImgMapper.updateInfoById(newPhoto);
        }
        return AjaxResult.success("更新虫情信息成功");
    }


}



